/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    /// <summary>
    /// Interaction logic for EmployeeTimePunches.xaml
    /// </summary>
    public partial class EmployeeTimePunches : UserControl
    {
        public static TIMESLIP _selectedTimePunch = null;
        private static int _listPageScrollIndex = 0;
        private const int CONST_LINE_ITEMS_PER_VIEW = 10;

        /// <summary>
        /// 
        /// </summary>
        public EmployeeTimePunches()
        {
            InitializeComponent();
            bClockoutEmployee.ButtonDownDelegate += new Button_95_50.FunctionButtonDownDelegate(ChangeUsersTimeSlips);
            listviewTimePunches.SelectionChanged += new SelectionChangedEventHandler(ListView_SelectionChanged);
            upButton.ShineButtonClicked += new RoutedEventHandler(upButton_ShineButtonClicked_NOTHROW);
            downButton.ShineButtonClicked += new RoutedEventHandler(downButton_ShineButtonClicked_NOTHROW);
            _selectedTimePunch = null;
        }

        public void SetDataContext(object obj)
        {
            listviewTimePunches.DataContext = obj;
        }

        /// <summary>
        /// Should be called whenever we delete an item from the customer ticket or
        /// add or scroll items.
        /// </summary>
        void UpdateTicketFocus()
        {
            ///Sanity bounds customerCheck even though it is done elsewhere often.
            if ((_listPageScrollIndex >= 0) && (_listPageScrollIndex < listviewTimePunches.Items.Count))
            {
                if (listviewTimePunches.Items != null && listviewTimePunches.Items.Count != 0)
                {
                    listviewTimePunches.ScrollIntoView(listviewTimePunches.Items[_listPageScrollIndex]);
                    ///Select the new item we just put focus on.
                    listviewTimePunches.SelectedItem = listviewTimePunches.Items[_listPageScrollIndex];
                    _selectedTimePunch = listviewTimePunches.SelectedItem as TIMESLIP;
                }
            }
            else
            {
                ///If we jump out of bounds then just set the index to zero.
                _listPageScrollIndex = 0;
            }
        }

        /// <summary>
        /// Scrolls the customers ticket up and down.
        /// </summary>
        /// <param Name="directionUp"></param>
        void ListScrollClicked(bool directionUp)
        {
            if (directionUp)
            {
                _listPageScrollIndex -= CONST_LINE_ITEMS_PER_VIEW;

                ///Since we just went ahead and knocked off an entire view panels worth, we
                ///need to assure we didn't drive negative.
                if (_listPageScrollIndex < 0)
                {
                    _listPageScrollIndex = 0;
                }
            }
            else  ///Must be scroll down
            {
                _listPageScrollIndex += CONST_LINE_ITEMS_PER_VIEW;

                ///Make sure we didn't go too far, correct if we did by placing the view 
                ///at the end.
                if (_listPageScrollIndex >= listviewTimePunches.Items.Count)
                {
                    _listPageScrollIndex = listviewTimePunches.Items.Count - 1;
                }
            }
            UpdateTicketFocus();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        void upButton_ShineButtonClicked_NOTHROW(object sender, RoutedEventArgs e)
        {
            try
            {
                ListScrollClicked(true);
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        void downButton_ShineButtonClicked_NOTHROW(object sender, RoutedEventArgs e)
        {
            try
            {
                ListScrollClicked(false);
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dontCare"></param>
        private void ChangeUsersTimeSlips(int dontCare)
        {
            try
            {
                if (_selectedTimePunch == null)
                {
                    UMD.ShowGuiMessageSTASafe_NOTHROW("Please highlight a timepunch row before using this function.");
                }
                else
                {
                    USER user = SHIFT.GlobalContext.USERS.Where(u => u.Id == _selectedTimePunch.UserId).FirstOrDefault();
                    AdjustClockInOrOut ynb = new AdjustClockInOrOut("Would you like to adjust " +
                    user.FirstName + " " + user.LastName + "'s clock in time or clock out time?");
                    ynb.ShowDialog();

                    if (AdjustClockInOrOut.LastResponse == ClockInOrOutResponse.OUT)
                    {
                        DateTimePicker dtm = new DateTimePicker(
                            false, 
                            false, 
                            false, 
                            false, 
                            true, 
                            "Please Select a Clock Out Date and Time",
                            _selectedTimePunch.ClockedOut);
                        dtm.ShowDialog();
                        if (DateTimePicker.LastResponse == UserResponse.YES)
                        {
                            if (DateTimePicker.LastStartSelectedDateTime > _selectedTimePunch.ClockedIn)
                            {
                                using (DominicaEntities context = new DominicaEntities(DominicaEntities.GetEfConString()))
                                {
                                    context.TIMESLIPS.Attach(_selectedTimePunch);
                                    _selectedTimePunch.ClockedOut = DateTimePicker.LastStartSelectedDateTime;
                                    context.SaveChanges();
                                    App.InvokeStartStoryBoard_NOTHROW();
                                    FixTimePunches.RefreshTimePunches(this);
                                }
                            }
                            else
                            {
                                UMD.ShowGuiMessageSTASafe_NOTHROW("You must select clock out time that is after the clock in time.");
                            }
                        }
                    }
                    else if (AdjustClockInOrOut.LastResponse == ClockInOrOutResponse.IN)
                    {
                        DateTimePicker dtm = new DateTimePicker(
                            false,
                            false,
                            false,
                            false,
                            true,
                            "Please Select a Clock In Date and Time",
                            _selectedTimePunch.ClockedIn);
                        dtm.ShowDialog();
                        if (DateTimePicker.LastResponse == UserResponse.YES)
                        {
                            if (DateTimePicker.LastStartSelectedDateTime < _selectedTimePunch.ClockedOut || _selectedTimePunch.ClockedOut == null)
                            {
                                using (DominicaEntities context = new DominicaEntities(DominicaEntities.GetEfConString()))
                                {
                                    context.TIMESLIPS.Attach(_selectedTimePunch);
                                    _selectedTimePunch.ClockedIn = DateTimePicker.LastStartSelectedDateTime;
                                    context.SaveChanges();
                                    App.InvokeStartStoryBoard_NOTHROW();
                                    FixTimePunches.RefreshTimePunches(this);
                                }
                            }
                            else
                            {
                                UMD.ShowGuiMessageSTASafe_NOTHROW("You must select clock in time that is before the clock out time.");
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
        }

        /// <summary>
        /// Update the selected payment as the user clicks through them.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;

            if (e.AddedItems.Count != 0)
            {
                _selectedTimePunch = e.AddedItems[0] as TIMESLIP;
            }
        }
    }
}
